package com.gqj.elec.service.impl;

import com.gqj.common.core.domain.entity.SysUser;
import com.gqj.common.exception.ServiceException;
import com.gqj.common.utils.DateUtils;
import com.gqj.common.utils.SecurityUtils;
import com.gqj.elec.domain.ElecMaterial;
import com.gqj.elec.domain.ElecMaterialIndetail;
import com.gqj.elec.domain.ElecMaterialOutdetail;
import com.gqj.elec.domain.ElecMaterialOutinfo;
import com.gqj.elec.mapper.ElecMaterialIndetailMapper;
import com.gqj.elec.mapper.ElecMaterialMapper;
import com.gqj.elec.mapper.ElecMaterialOutdetailMapper;
import com.gqj.elec.mapper.ElecMaterialOutinfoMapper;
import com.gqj.elec.service.IElecMaterialOutdetailService;
import com.gqj.elec.service.RedisStringService;
import com.gqj.elec.service.WebSocketServer;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;


import javax.websocket.Session;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import net.sf.json.JSONObject;

/**
 * 物资出库详情Service业务层处理
 *
 * @author lxq
 * @date 2023-12-17
 */
@Service
public class ElecMaterialOutdetailServiceImpl implements IElecMaterialOutdetailService {
    @Autowired
    private ElecMaterialOutdetailMapper elecMaterialOutdetailMapper;
    @Autowired
    private ElecMaterialMapper elecMaterialMapper;
    @Autowired
    private ElecMaterialOutinfoMapper elecMaterialOutinfoMapper;
    @Autowired
    private RedisStringService redis;

    @Autowired
    private ElecMaterialIndetailMapper elecMaterialIndetailMapper;

    // concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();

    /**
     * 查询物资出库详情
     *
     * @param outdetailId 物资出库详情主键
     * @return 物资出库详情
     */
    @Override
    public ElecMaterialOutdetail selectElecMaterialOutdetailByOutdetailId(Long outdetailId) {
        return elecMaterialOutdetailMapper.selectElecMaterialOutdetailByOutdetailId(outdetailId);
    }

    /**
     * 查询物资出库详情列表
     *
     * @param elecMaterialOutdetail 物资出库详情
     * @return 物资出库详情
     */
    @Override
    public List<ElecMaterialOutdetail> selectElecMaterialOutdetailList(ElecMaterialOutdetail elecMaterialOutdetail) {
        return elecMaterialOutdetailMapper.selectElecMaterialOutdetailList(elecMaterialOutdetail);
    }

    /**
     * 新增物资出库详情
     *
     * @param elecMaterialOutdetail 物资出库详情
     * @return 结果
     */
    @Override
    public int insertElecMaterialOutdetail(ElecMaterialOutdetail elecMaterialOutdetail) {
        elecMaterialOutdetail.setCreateTime(DateUtils.getNowDate());
        return elecMaterialOutdetailMapper.insertElecMaterialOutdetail(elecMaterialOutdetail);
    }

    /**
     * 修改物资出库详情
     *
     * @param elecMaterialOutdetail 物资出库详情
     * @return 结果
     */
    @Override
    public int updateElecMaterialOutdetail(ElecMaterialOutdetail elecMaterialOutdetail) {
        elecMaterialOutdetail.setUpdateTime(DateUtils.getNowDate());
        return elecMaterialOutdetailMapper.updateElecMaterialOutdetail(elecMaterialOutdetail);
    }

    /**
     * 批量删除物资出库详情
     *
     * @param outdetailIds 需要删除的物资出库详情主键
     * @return 结果
     */
    @Override
    public int deleteElecMaterialOutdetailByOutdetailIds(Long[] outdetailIds) {
        return elecMaterialOutdetailMapper.deleteElecMaterialOutdetailByOutdetailIds(outdetailIds);
    }

    /**
     * 删除物资出库详情信息
     *
     * @param outdetailId 物资出库详情主键
     * @return 结果
     */
    @Override
    public int deleteElecMaterialOutdetailByOutdetailId(Long outdetailId) {
        return elecMaterialOutdetailMapper.deleteElecMaterialOutdetailByOutdetailId(outdetailId);
    }

    /**
     * 执行物资出库
     *
     * @param elecMaterialOutdetailList 物资出库详情集合
     * @return 结果
     */
    @Override
    public int elecMaterialOutStorage(List<ElecMaterialOutdetail> elecMaterialOutdetailList) {
        for (ElecMaterialOutdetail elecMaterialOutdetail : elecMaterialOutdetailList) {
            Long outDetailId = elecMaterialOutdetail.getOutdetailId();
            Long materialId = elecMaterialOutdetail.getMaterialId();
            if (null == outDetailId || outDetailId == 0) {
                continue;
            }
            if (null == materialId || materialId == 0) {
                continue;
            }

            ElecMaterialOutdetail detail = new ElecMaterialOutdetail();
            detail.setOutdetailId(outDetailId);
            detail.setIsOut("1");
            elecMaterialOutdetailMapper.updateElecMaterialOutdetail(detail);

            ElecMaterial elecMaterial = new ElecMaterial();
            elecMaterial.setMaterialId(materialId);
            elecMaterial.setMaterialStatus("2");
            elecMaterialMapper.updateElecMaterial(elecMaterial);
        }

        Long outId = elecMaterialOutdetailList.get(0).getOutId();
        ElecMaterialOutdetail elecMaterialOutdetail = new ElecMaterialOutdetail();
        elecMaterialOutdetail.setOutId(outId);
        elecMaterialOutdetail.setIsOut("0");
        List<ElecMaterialOutdetail> elecMaterialOutdetails = elecMaterialOutdetailMapper.selectElecMaterialOutdetailList(elecMaterialOutdetail);
        if (null == elecMaterialOutdetails || elecMaterialOutdetails.size() == 0) {
            ElecMaterialOutinfo elecMaterialOutinfo = new ElecMaterialOutinfo();
            elecMaterialOutinfo.setOutId(outId);
            elecMaterialOutinfo.setOutStatus("3");
            elecMaterialOutinfoMapper.updateElecMaterialOutinfo(elecMaterialOutinfo);
        } else {
            ElecMaterialOutinfo elecMaterialOutinfo = new ElecMaterialOutinfo();
            elecMaterialOutinfo.setOutId(outId);
            elecMaterialOutinfo.setOutStatus("2");
            elecMaterialOutinfoMapper.updateElecMaterialOutinfo(elecMaterialOutinfo);
        }
        return 0;
    }

    /**
     * 执行物资出库
     *
     * @param elecMaterialOutdetailList 物资出库详情集合
     * @return 结果
     */
    @Override
    public int elecMaterialReturnStorage(List<ElecMaterialOutdetail> elecMaterialOutdetailList) {
        for (ElecMaterialOutdetail elecMaterialOutdetail : elecMaterialOutdetailList) {
            Long outDetailId = elecMaterialOutdetail.getOutdetailId();
            Long materialId = elecMaterialOutdetail.getMaterialId();
            if (null == outDetailId || outDetailId == 0) {
                continue;
            }
            if (null == materialId || materialId == 0) {
                continue;
            }

            ElecMaterialOutdetail detail = new ElecMaterialOutdetail();
            detail.setOutdetailId(outDetailId);
            detail.setIsReturn("1");
            elecMaterialOutdetailMapper.updateElecMaterialOutdetail(detail);

            ElecMaterial elecMaterial = new ElecMaterial();
            elecMaterial.setMaterialId(materialId);
            elecMaterial.setMaterialStatus("1");
            elecMaterialMapper.updateElecMaterial(elecMaterial);
        }

        Long outId = elecMaterialOutdetailList.get(0).getOutId();
        ElecMaterialOutdetail elecMaterialOutdetail = new ElecMaterialOutdetail();
        elecMaterialOutdetail.setOutId(outId);
        elecMaterialOutdetail.setIsReturn("0");
        List<ElecMaterialOutdetail> elecMaterialOutdetails = elecMaterialOutdetailMapper.selectElecMaterialOutdetailList(elecMaterialOutdetail);
        if (null == elecMaterialOutdetails || elecMaterialOutdetails.size() == 0) {
            ElecMaterialOutinfo elecMaterialOutinfo = new ElecMaterialOutinfo();
            elecMaterialOutinfo.setOutId(outId);
            elecMaterialOutinfo.setOutStatus("4");
            elecMaterialOutinfoMapper.updateElecMaterialOutinfo(elecMaterialOutinfo);
        }
        return 0;
    }


    /**
     * 处理设备返回的标签数据
     **/
    @Transactional
    @Override
    public int analysisTdm(String epc, int port) {
        epc = epc.substring(0, 12);

        Map<String, Object> statisticsMap = new HashMap();
//        Jedis jedis = new Jedis("192.168.1.22");
//        jedis.auth("123456");
        SimpleDateFormat sd = new SimpleDateFormat();
        Date date = DateUtils.getNowDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(date);
        int i = 0;
//        if (null == redis.getRedis(epc) || "".equals(redis.getRedis(epc))) {
            ElecMaterial entity = elecMaterialMapper.queryByRfidCode(epc);
            if (null != entity) {
                Long materialId = entity.getMaterialId();

                String materialStatus = entity.getMaterialStatus();
//                redis.setRedis(epc, epc, 20);
//
              //  if (null != redis.getRedis(epc) && !"".equals(redis.getRedis(epc))) {
                    //查询工器具详情
                    if ("1".equals(materialStatus)) {// 领用
                        //if (stockStatus == 1|| stockStatus == 0) {
                        //实例化出入记录实体，准备记录出入信息
                        ElecMaterialOutdetail emo = new ElecMaterialOutdetail();
                        emo.setMaterialId(materialId);
                        emo.setIsOut("1");
                        emo.setMaterialStatus("1");
                        emo.setMaterialId(materialId);
                        emo.setMaterialCode(entity.getMaterialCode());
                        emo.setMaterialName(entity.getMaterialName());
                        emo.setOutDateStr(formattedDate);
                        statisticsMap.put("out", emo);
                        statisticsMap.put("key", "material_out");

                    } else if ("2".equals(materialStatus)) {
                        ElecMaterialIndetail emi = new ElecMaterialIndetail();
                        emi.setMaterialId(materialId);
                        emi.setIsIn("1");
                        emi.setMaterialCode(entity.getMaterialCode());
                        emi.setMaterialName(entity.getMaterialName());
                        emi.setMaterialStatus("2");
                        emi.setInDateStr(formattedDate);
                        statisticsMap.put("in", emi);
                        statisticsMap.put("key", "material_in");

                    }

                    // 实时推送数据
                    JSONObject jsonObject = JSONObject.fromObject(statisticsMap);
                    try {
                        WebSocketServer.sendInfo(jsonObject.toString());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
              //  }
            }
//        }
        return 0;
    }

    /**
     * 处理通道门识别的物资信息
     **/
    @Override
    public int detailMaterialInfo(ElecMaterialOutdetail elecMaterialOutdetail) {
        String username = SecurityUtils.getUsername();
        if (elecMaterialOutdetail.getElecMaterialOutdetailList().size() <= 0) {
            throw new ServiceException("工器具列表不能为空");
        }
        for (ElecMaterialOutdetail elecMaterial : elecMaterialOutdetail.getElecMaterialOutdetailList()
        ) {
            ElecMaterial material = elecMaterialMapper.selectElecMaterialByMaterialId(elecMaterial.getMaterialId());
            if (null == material) {
                throw new ServiceException("工器具不存在");
            }
            if ("1".equals(material.getMaterialStatus())) {
                ElecMaterialOutdetail detailOut = new ElecMaterialOutdetail();
                detailOut.setMaterialId(elecMaterial.getMaterialId());
                detailOut.setIsOut("1");
                detailOut.setOutDate(DateUtils.getNowDate());
                detailOut.setCreateBy(username);
                detailOut.setCreateTime(DateUtils.getNowDate());
                elecMaterialOutdetailMapper.insertElecMaterialOutdetail(detailOut);
                elecMaterialMapper.updateStatus(material.getMaterialId(), 2);
            } else if ("2".equals(material.getMaterialStatus())) {
                ElecMaterialIndetail detailIn = new ElecMaterialIndetail();
                detailIn.setMaterialId(elecMaterial.getMaterialId());
                detailIn.setIsIn("1");
                detailIn.setInDate(DateUtils.getNowDate());
                detailIn.setCreateBy(username);
                detailIn.setCreateTime(DateUtils.getNowDate());
                elecMaterialIndetailMapper.insertElecMaterialIndetail(detailIn);
                elecMaterialMapper.updateStatus(material.getMaterialId(), 1);
            }
        }
        return 0;
    }
}
